<?php

namespace App\Service;

use App\Model\SaMenu;
use App\Model\SaPermission;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;

class MenuService
{
    /**
     * 根据Id获取菜单信息.
     *
     * @param $id
     *
     * @return array|bool
     */
    public static function getInfoById($id)
    {
        if ($id <= 0) {
            return [];
        }

        return SaMenu::getInfo(['id' => $id]);
    }

    /**
     * 添加菜单.
     *
     * @param $param
     *
     * @return mixed
     */
    public static function addMenu($param)
    {
        // 参数验证
        throw_if(!$param['name'], new ApiException('请输入菜单名称'));
        throw_if(!$param['alias'], new ApiException('请输入菜单别名'));
        throw_if(0 == $param['parent_id'] && !$param['icon'], new ApiException('请输入菜单图标类名'));
        throw_if($param['sort'] < 0, new ApiException('请输入正确的排序值'));
        $loginAdmin           = HelperClass::getLoginAdmin();
        $param['creator_id']  = $loginAdmin['id'];
        $param['creator']     = $loginAdmin['username'];

        return SaMenu::addMenu($param);
    }

    /**
     * 编辑菜单.
     *
     * @param $id
     * @param $param
     *
     * @return mixed
     */
    public static function editMenu($id, $param)
    {
        throw_if(!$param['name'], new ApiException('请输入菜单名称'));
        throw_if(!$param['alias'], new ApiException('请输入菜单别名'));
        throw_if(0 == $param['parent_id'] && !$param['icon'], new ApiException('请输入菜单图标类名'));
        throw_if($param['sort'] < 0, new ApiException('请输入正确的排序值'));

        return SaMenu::editMenu($id, $param);
    }

    /**
     * 删除菜单.
     *
     * @param $id
     *
     * @return true
     */
    public static function delMenuById($id)
    {
        // 判断是否有子菜单
        $count = SaMenu::getCount(['parent_id' => $id]);
        throw_if($count, new ApiException('此菜单有子菜单，无法删除'));

        DB::beginTransaction();
        try {
            SaMenu::delMenu($id);
            SaPermission::delPermissionByMenu($id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            throw_if(true, new ApiException('操作失败，请稍后重试'));
        }

        return true;
    }
}
